<?php
Zend_loader::loadClass('Zend_Controller_Action');
Zend_loader::loadClass('Zend_Rest_Client');

class TermExtractionController extends Zend_Controller_Action
{
	/**
	 * The default action
	 */
    public function termExtractionAction() 
    {
        $this->view->token = Zend_Registry::get('session')->token;
        $this->render();
    }

    public function extractAction() 
    {
		if ($this->getRequest()->isPost()) {
			$token = Zend_Filter::get($this->getRequest()->getPost('token'), 'StripTags');
			//if (!empty($token) and $token == Zend_Registry::get('session')->token) {
				
				$url = Zend_Filter::get($this->getRequest()->getPost('url'), 'StripTags');
				$page = @file_get_contents($url);
				
				if (!empty($page)) {
					$matches = array();
					if (preg_match('/<body[^>]*>(.*?)<\/body\s*/isx', $page, $matches)) {
						$content = $matches[1];

						$content = preg_replace('/(<style[^>]*>[^>]*<\/style\s*>)/isx', '', $content);
						$content = preg_replace('/(<script[^>]*>[^>]*<\/script\s*>)/isx', '', $content);
						$content = preg_replace('/(&.*?;)/isx', '', $content);
						$content = Zend_Filter::get($content, 'StripTags');

						$client = new Zend_Rest_Client('http://search.yahooapis.com/ContentAnalysisService/V1/termExtraction');
						$client->appid('rqP7px7V34L2DVtFJq04ZFTHgiRJQmlvnQze7T313MFdGLAy1.lw8PZBWeRqk40R_30')->context($content)->output('xml');
						$result = $client->post();
						$client = null;

						$this->view->url = $url ;

                        if (!empty($result->Result)) {
                            $counter = 1;
                            $r = array();
                            foreach($result->Result as $item) {
                                $r[] = $counter++ . ' : ' . $this->view->escape($item);
                            }
                            $this->view->result = $r;
                        }

                    } else {
						$this->view->url = $url ;
					}
				}
//			} else {
//				return FALSE;
//			}
		}
    }
}